package httpserver;

import java.io.IOException;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.*;

/**
 * Class for parsing information to the Respons class. This is the actual Server
 * @version 1.0
 * @author Casper, Jackie, Jacob og Dennis.
 */
public class Server implements Runnable{

    public final static Logger LOGGER = Logger.getLogger("");
    private static Handler fh;
    private ConfigHandler cfgHandl;
    private boolean running;
    private Socket clientSocket;
    private static ServerSocket serverSocket;
    private ExecutorService threadPool;

    /**
     * Constructor for Server, that also sets the Logger and the format of the logger.
     * @throws IOException
     */

    public Server() throws IOException {
        cfgHandl = new ConfigHandler();
        fh = new FileHandler("./src/httpserver/log/logging.log");
        fh.setFormatter(new SimpleFormatter());
        LOGGER.addHandler(fh);
        running = true;
    }

    /**
     * This method starts the serversocket and creates the threadpool.<br>
     * Ultimately it runs the while loop where it accepts incoming client and<br>
     * creates an response object and executes it in the created threadpool.
     * @throws IOException
     */
    private void start() throws IOException {
        serverSocket = new ServerSocket(cfgHandl.getPort());
        LOGGER.info("Server started!");
        threadPool = Executors.newCachedThreadPool();
        while (running) {
            clientSocket = serverSocket.accept();
            Response response = new Response(clientSocket);
            threadPool.execute(response);
        }     
    }

    /**
     *
     * @param status is set to false when the server is set to shutdown.
     */
    public void setRunning(Boolean status){
        running = status;
    }

    /**
     * Method to access the serversockets setSoTimeout method, and invoke<br>
     * the shutdown method on the cached threadpool.
     * @param millisec , this parameter is set to determine how many<br>
     * milliseconds that has to pass before the server socket times out.
     * @throws SocketException
     */
    public void setSocketTimeout(int millisec) throws SocketException, IOException{
        threadPool.shutdown();
        serverSocket.setSoTimeout(millisec);
        serverSocket.close();
    }

    /**
     * Abstract method implemented from the Runnable interface to enable<br>
     * the class running in a thread.
     */
    public void run() {
        try {
            start();
        } catch (IOException ex) {
            LOGGER.log(Level.WARNING, "Exception on server start up", ex);
        }
    }
}
